#!/usr/bin/env python3

import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QLineEdit, QPushButton,
    QFileDialog, QVBoxLayout, QHBoxLayout, QMessageBox, QCheckBox
)
from pathlib import Path

class ShortcutCreator(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("快捷方式生成器")

        layout = QVBoxLayout()

        # 应用名输入
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入应用名称")
        layout.addWidget(QLabel("应用名称:"))
        layout.addWidget(self.name_input)

        # 脚本路径输入
        script_layout = QHBoxLayout()
        self.script_input = QLineEdit()
        self.script_input.setPlaceholderText("选择启动脚本路径")
        script_button = QPushButton("选择脚本")
        script_button.clicked.connect(self.select_script)
        script_layout.addWidget(self.script_input)
        script_layout.addWidget(script_button)
        layout.addLayout(script_layout)

        # 图标路径输入
        icon_layout = QHBoxLayout()
        self.icon_input = QLineEdit()
        self.icon_input.setPlaceholderText("选择图标路径")
        icon_button = QPushButton("选择图标")
        icon_button.clicked.connect(self.select_icon)
        icon_layout.addWidget(self.icon_input)
        icon_layout.addWidget(icon_button)
        layout.addLayout(icon_layout)

        # 终端复选框
        self.terminal_checkbox = QCheckBox("启动时打开终端")
        self.terminal_checkbox.setChecked(True)
        layout.addWidget(self.terminal_checkbox)

        # 快捷方式按钮
        button_layout = QHBoxLayout()
        desktop_btn = QPushButton("创建桌面快捷方式")
        global_btn = QPushButton("创建应用快捷方式")
        desktop_btn.clicked.connect(self.create_desktop_shortcut)
        global_btn.clicked.connect(self.create_user_launcher_shortcut)
        button_layout.addWidget(desktop_btn)
        button_layout.addWidget(global_btn)
        layout.addLayout(button_layout)

        self.setLayout(layout)

    def select_script(self):
        path, _ = QFileDialog.getOpenFileName(self, "选择启动脚本", "", "脚本文件 (*.py *.sh *.AppImage);;所有文件 (*)")
        if path:
            self.script_input.setText(path)

    def select_icon(self):
        path, _ = QFileDialog.getOpenFileName(self, "选择图标", "", "图标文件 (*.png *.ico *.svg *.xpm);;所有文件 (*)")
        if path:
            self.icon_input.setText(path)

    def get_desktop_path(self):
        # 支持 Desktop 和 桌面
        possible_names = ["Desktop", "桌面"]
        for name in possible_names:
            path = Path.home() / name
            if path.exists():
                return path
        # fallback: 尝试 xdg-user-dir
        xdg_path = os.popen("xdg-user-dir DESKTOP").read().strip()
        return Path(xdg_path) if xdg_path else Path.home()

    def create_desktop_file(self, target_path):
        name = self.name_input.text().strip()
        script_path = self.script_input.text().strip()
        icon_path = self.icon_input.text().strip()
        open_terminal = self.terminal_checkbox.isChecked()

        if not (name and script_path):
            QMessageBox.warning(self, "错误", "请填写应用名称并选择启动脚本路径")
            return

        desktop_entry = f"""[Desktop Entry]
Name={name}
Exec={script_path}
Icon={icon_path if icon_path else 'utilities-terminal'}
Terminal={'true' if open_terminal else 'false'}
Type=Application
Categories=Utility;
"""
        try:
            with open(target_path, 'w') as f:
                f.write(desktop_entry)
            os.chmod(target_path, 0o755)
            QMessageBox.information(self, "成功", f"已创建快捷方式：{target_path}")
            print(f"✅ 快捷方式已生成: {target_path}")
            print(f"🗑️ 若需删除：运行命令：rm '{target_path}'")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"创建失败：{e}")

    def create_desktop_shortcut(self):
        desktop_path = self.get_desktop_path()
        target = desktop_path / f"{self.name_input.text().strip()}.desktop"
        self.create_desktop_file(str(target))

    def create_user_launcher_shortcut(self):
        app_path = Path.home() / ".local/share/applications"
        app_path.mkdir(parents=True, exist_ok=True)
        target = app_path / f"{self.name_input.text().strip()}.desktop"
        self.create_desktop_file(str(target))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ShortcutCreator()
    window.show()
    sys.exit(app.exec_())

